<template>
	<view class="container">
		<!-- 空白页 -->
		<view v-if="!user.userInfo.id || empty===true" class="empty">
			<image src="/static/emptyCart.jpg" mode="aspectFit"></image>
			<view v-if="user.userInfo.id" class="empty-tips">
				空空如也
				<navigator class="navigator" v-if="user.userInfo.id" url="../../home" open-type="switchTab">随便逛逛></navigator>
			</view>
			<view v-else class="empty-tips">
				空空如也
				<view class="navigator" @click="navToLogin">去登录></view>
			</view>
		</view>
		<view v-else>
			<!-- 列表 -->
			<view class="cart-list" v-for="(cart, storeId) in dataList" :key="cart.id">
				<view class="title">
					{{cart.storeInfo.title}}
				</view>
				<block v-for="(item, index) in cart.skuList" :key="item.id">
					<view
						class="cart-item"
						:class="{'b-b': index!==cart.skuList.length-1}">
						<view class="image-wrapper">
							<navigator :url="'/pages/ishop/item/info?id=' + item.itemId">
								<xy-image :src="item.itemInfo.cover"
									class="loaded"
									mode="aspectFill"
									@load="onImageLoad('dataList', storeId, index)"
									@error="onImageError('dataList', storeId, index)">
								</xy-image>
							</navigator>
							<view 
								class="xyicon xyicon-success checkbox"
								:class="{checked: item.checked}"
								@click="check('item', storeId, index)"
							></view>
						</view>
						<view class="item-right">
							<text class="clamp title">{{item.itemInfo.title}}</text>
							<text class="attr">{{item.skuSpec}}</text>
							<view class="price-num flex">
								<view class="price">¥{{item.price}}</view>
								<xy-number-box
									class="step uni-number-box-round"
									:min="1"
									:max="item.stock"
									v-model="item.amount"
									@change="numberChange"
								></xy-number-box>
							</view>
						</view>
						<text class="del-btn xyicon xyicon-close" @click="deleteCartItem(storeId,index)"></text>
					</view>
				</block>
			</view>
			<!-- 底部菜单栏 -->
			<view class="action-section">
				<view class="checkbox">
					<image
						:src="allChecked?'/static/selected.png':'/static/select.png'"
						mode="aspectFit"
						@click="check('all')"
					></image>
					<view class="checkall" :class="{show: !allChecked}">
						全选
					</view>
					<view class="clear-btn" :class="{show: allChecked}" @click="clearCart">
						清空
					</view>
				</view>
				<view class="total-box">
					<view class="price">¥{{total}}</view>
					<view class="coupon">
						<text>已优惠</text>
						<text>0.00</text>
						<text>元</text>
					</view>
				</view>
				<button type="primary" class="no-border confirm-btn" @click="createOrder">去结算</button>
			</view>
		</view>
		<view class="guess-you-like flex text-primary">
			<view>——</view>
			<view class="title m-l-sm m-r-sm">
				<text class="xyicon xyicon-heart inline-block m-r-xs"></text>
				<text>猜你喜欢</text>
			</view>
			<view>——</view>
		</view>
		<view class="item-list-section">
			<view
				v-for="(item, index) in guessLikeList" :key="index"
				class="guess-item"
				@click="navToDetailPage(item)">
				<view class="image-wrapper">
					<xy-image :src="item.cover" mode="aspectFill"></xy-image>
				</view>
				<text class="title clamp">{{item.title}}</text>
				<text class="price">￥{{item.price}}</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {mapState, mapMutations} from 'vuex'
	export default {
		data() {
			return {
				total: 0, //总价格
				allChecked: false, //全选状态  true|false
				empty: false, //空白页现实  true|false
				dataList: [],
				orderInfo: {},
				guessLikeList: [] ,//猜你喜欢列表,
				checkedItemCount: 0
			};
		},
		onLoad(){
			this.getGuessLike();
		},
		onShow(){
			this.loadData();
		},
		watch:{
			// 显示空白页
			dataList(e){
				let empty = e.length === 0 ? true: false;
				if(this.empty !== empty){
					this.empty = empty;
				}
			}
		},
		computed:{
			...mapState(['app', 'user'])
		},
		async onPullDownRefresh() {
			await this.loadData();
			uni.stopPullDownRefresh();
			setTimeout(function () {
				uni.stopPullDownRefresh();
			}, 5000);
		},
		onShareAppMessage(res) {
			if (res.from === 'button') {// 来自页面内分享按钮
				console.log(res.target)
			}
			return {
				title: this.$store.state.app.siteInfo.title,
				path: '/pages/ishop/cart/my'
			}
		},
		methods: {
			async getGuessLike(){
				// 猜你喜欢
				let res5 = await this.util.request({
					url: '/v1/ishop/item/lists',
					method: 'get',
					data: {
						limit: 4,
						iadTag: 'cart_rec'
					}
				});
				if (res5.code == 200) {
					this.guessLikeList = res5.data.dataList;
				}
			},
			//请求数据
			async loadData(){
				if (this.$store.state.user.token) {
					let res = await this.util.request({
						url: '/v1/ishop/cart/my',
						method: 'get',
					});
					if (res.code == 200) {
						this.dataList = res.data.dataList;
					}
					// console.log(this.dataList)
					this.calcTotal();  //计算总价
				}
			},
			//监听image加载完成
			onImageLoad(data, storeId, index) {
				console.log('onImageLoad', storeId)
				this.$set(this[data][storeId]['skuList'][index], 'loaded', 'loaded');
			},
			//监听image加载失败
			onImageError(data, storeId, index) {
				this[data][storeId]['skuList'][index]['itemInfo'].cover = '/static/errorImage.jpg';
			},
			navToLogin(){
				uni.navigateTo({
					url: '/pages/core/user/login'
				})
			},
			//详情页
			navToDetailPage(item) {
				let url = item.url;
				uni.navigateTo({
					url: '/pages/ishop/item/info?' + 'id=' + item.id
				})
			},
			 //选中状态处理
			check(type, storeId, index){
				if(type === 'item'){
					this.dataList[storeId].skuList[index].checked
						= !this.dataList[storeId].skuList[index].checked;
				} else {
					const checked = !this.allChecked;
					for (let storeId in this.dataList) {
						this.dataList[storeId].skuList.forEach(item1=>{
							item1.checked = checked;
						})
					}
					this.allChecked = checked;
				}
				this.calcTotal(type);
			},
			//数量
			numberChange(data){
				this.calcTotal();
			},
			//删除
			async deleteCartItem(storeId,index){
				let res = await this.util.request({
					url: '/v1/ishop/cart/delete/' + this.dataList[storeId].skuList[index].id,
					method: 'delete',
				});
				if (res.code == 200) {
					this.dataList[storeId].skuList.splice(index, 1);
					this.calcTotal();
					uni.hideLoading();
					this.util.showToast({
						title: res.msg,
						icon: 'success',
						duration: 1000
					});
				} else {
					this.util.showToast({
						title: res.msg,
						icon: 'loading',
						duration: 2000
					});
				}
			},
			//清空
			clearCart(){
				uni.showModal({
					content: '清空购物车？',
					success: async (e)=>{
						if(e.confirm){
							let res = await this.util.request({
								url: '/v1/ishop/cart/deleteAll',
								method: 'delete',
							});
							if (res.code == 200) {
								this.dataList = [];
								this.util.showToast({
									title: res.msg,
									icon: 'success',
									duration: 1000
								});
							} else {
								this.util.showToast({
									title: res.msg,
									icon: 'loading',
									duration: 2000
								});
							}
						}
					}
				});
			},
			//计算总价
			calcTotal(){
				if(this.dataList.length === 0){
					this.empty = true;
					return;
				}
				let total = 0;
				let orderInfo = new Object();
				let checked = true;
				this.checkedItemCount = 0;
				for (let storeId in this.dataList) {
					let skuList = new Array();
					this.dataList[storeId].skuList.forEach(item1=>{
						if (item1.checked === true) {
							this.checkedItemCount ++;
							console.log(item1);
							skuList.push({
								'itemId': item1.itemId,
								'skuId': item1.skuId,
								'amount': item1.amount,
								'cartId': item1.id
							});
							total += item1.price * item1.amount;
						} else if (checked === true) {
							checked = false;
						}
					});
					orderInfo[storeId] = {
						'skuList': skuList
					}
				}
				this.orderInfo = orderInfo;
				console.log(orderInfo);
				this.allChecked = checked;
				this.total = Number(total.toFixed(2));
			},
			// 创建订单
			createOrder(){
				console.log(this.orderInfo);
				console.log(this.checkedItemCount);
				if (this.checkedItemCount <= 0) {
					uni.showToast({
						title: '请选择商品'
					})
					return;
				}
				uni.navigateTo({
					url: `/pages/ishop/order/create?data=${JSON.stringify({
						orderInfo: this.orderInfo
					})}`
				});
			}
		}
	}
</script>

<style lang='scss' scoped>
	navigator {
		height: 100%;
	}
	.container {
		padding-bottom: calc(50px + var(--window-bottom));
		/* 空白页 */
		.empty{
			left: 0;
			top:0;
			width: 100%;
			height: 200px;
			padding-bottom:100upx;
			display:flex;
			justify-content: center;
			flex-direction: column;
			align-items:center;
			background: #fff;
			image{
				width: 240upx;
				height: 160upx;
				margin-bottom:30upx;
			}
			.empty-tips{
				display:flex;
				font-size: $font-sm+2upx;
				color: $font-color-disabled;
				.navigator{
					color: $uni-color-primary;
					margin-left: 16upx;
				}
			}
		}
	}
	.cart-list {
		margin: 10px 10px 0;
		background-color: #fff;
		border-radius: 8px;
		>.title {
			display: flex;
			padding: 0 10px;
			align-items: center;
			height: 40px;
			font-size: 13px;
		}
		/* 购物车列表项 */
		.cart-item{
			display:flex;
			position:relative;
			padding: 10px 5px 10px 15px;
			.image-wrapper{
				width: 85px;
				height: 85px;
				flex-shrink: 0;
				position:relative;
				image{
					border-radius: 4px;
				}
			}
			.checkbox {
				position:absolute;
				left:-16upx;
				top: -16upx;
				z-index: 8;
				font-size: 44upx;
				line-height: 1;
				padding: 4upx;
				color: $font-color-disabled;
				background:#fff;
				border-radius: 50px;
			}
			.item-right{
				margin-left: 10px;
				display:flex;
				flex-direction: column;
				flex: 1;
				overflow: hidden;
				position:relative;
				.title {
					color: $font-color-dark;
					font-size: 12px;
					line-height: 14px;
				}
				.attr{
					width: fit-content;
					background-color: #F5F6F7;
					padding: 1px 6px;
					font-size: 12px;
					color: $font-color-light;
					margin: 8px 0;
					display: inline-block;
				}
				.price-num {
					justify-content: space-between;
					align-items: center;
					.price {
						font-size: 14px;
						font-weight: 400;
						color: $uni-color-primary;
					}
				}
			}
			.del-btn{
				border-radius: 50%;
				padding: 2px 5px;
				font-size: 12px; 
				height: 12px;
				color: $font-color-light;
			}
		}
	}
	.guess-you-like {
		justify-content: center;
		align-items: center;
		height: 40px;
		margin-top: 10px;
	}
	/* 底部栏 */
	.action-section{
		position:fixed;
		left: 0;
		right: 0;
		margin-left: auto;
		margin-right: auto;
		bottom:calc(var(--window-bottom));
		z-index: 95;
		display: flex;
		align-items: center;
		height: 50px;
		padding: 0 15px;
		background: rgba(255,255,255,.9);
		.checkbox{
			height: 20px;
			flex: 1;
			position:relative;
			image {
				width: 20px;
				height: 100%;
				position:relative;
				z-index: 5;
			}
			.checkall {
				position:absolute;
				left: 13px;
				top: 0;
				z-index: 4;
				width: 50px;
				height: 20px;
				line-height: 20px;
				padding-left: 12px;
			}
			.clear-btn{
				position:absolute;
				left: 13px;
				top: 0;
				z-index: 4;
				width: 0;
				height: 20px;
				line-height: 20px;
				padding-left: 19px;
				font-size: $font-base;
				color: #fff;
				background: $font-color-disabled;
				border-radius:0 50px 50px 0;
				display: none;
				transition: .2s;
				&.show{
					display: block;
					width: 60px;
				}
			}
		}
		.total-box{
			display:flex;
			flex-direction: column;
			text-align:right;
			padding-right: 20px;
			.price {
				font-size: 16px;
				height: 18px;
				color: $uni-color-primary;
			}
			.coupon {
				font-size: $font-sm;
				color: $font-color-light;
				text {
					color: $font-color-dark;
				}
			}
		}
		.confirm-btn {
			padding: 0 10px;
			margin: 0;
			border-radius: 100px;
			height: 30px;
			line-height: 30px;
			font-size: 14px;
			background: $uni-color-primary;
			box-shadow: 1px 2px 5px rgba(217, 60, 93, 0.72);
		}
	}
	/* 复选框选中状态 */
	.action-section .checkbox.checked,
	.cart-item .checkbox.checked{
		color: $uni-color-primary;
	}
</style>
